public class SubDomainVisit(){
    public List<String> subdomainVisits(String[] cpdomains) {
        Map<String, Integer> counts = new HashMap<String, Integer>();
        for (String cpdomain : cpdomains) {
            String[] domainInfo = cpdomain.split("\\s+");
            int count = Integer.valueOf(domainInfo[0]).intValue();
            String domain = domainInfo[1];
            String[] flags = domain.split("\\.");
            String subDomain = "";           
            for (int i = flags.length - 1; i >= 0; i --) {
                subDomain = flags[i] + ((i == flags.length - 1)?"":"." + subDomain);
                counts.put(subDomain, counts.getOrDefault(subDomain, 0) + count);
            }
        }
        List<String> ans = new ArrayList<String>();
        for(String dom : counts.keySet()) {
            ans.add("" + counts.get(dom) + " " + dom);
        }
        return ans;
    }
}